const { delDir, mkdirpSync } = require("./utils");
const fs = require("fs");
const { analyseObj, mergeObj } = require("./contentProcessing");
const prettier = require("prettier");
const llmFetch = require("./llmFetch");
/**
 * 中文包转英文
 * @param {*} context
 * @returns
 */
const translateEnLang = async (context) => {
  console.log(
    `==== [start] [task=${context.contextFiles.length}] translateEnLang fn `
  );
  delDir(context.translateEnDir);
  for (const [index, file] of context.contextFiles.entries()) {
    if (file.translateStatus === false) {
      console.log(`==== [continue] [task=${index + 1}] translateLang`);
      console.log(JSON.stringify(file));
      continue;
    }
    console.log(`==== [start] [task=${index + 1}] translateLang`);
    const translateFile = fs.readFileSync(file.translatePath, "utf8");
    let translateStr = translateFile.replace("export default ", "");
    translateStr = await prettier.format(translateStr, {
      parser: "json",
    });
    const translate = fs.readFileSync(context.tplTranslateEn, "utf8");
    try {
      const result = await Promise.all(
        analyseObj(translateStr).map(async (obj) => {
          const { data } = await llmFetch(
            context.key,
            translate.replace("{{REQUEST_STR}}", JSON.stringify(obj, null, 2))
          );
          const str = data.choices?.[0]?.message?.content
            .replace(/\n/g, "")
            .replace(/.*```json/, "")
            .replace(/```.*/, "");
          // .replace("```json", "")
          // .replace("```", "");
          return JSON.parse(str);
        })
      );

      const formattedCode = await prettier.format(
        `export default ${JSON.stringify(mergeObj(result), null, 2)}`,
        {
          parser: "babel",
          ...(context.prettier || {}),
        }
      );
      mkdirpSync(file.translateEnDir);
      fs.writeFileSync(file.translateEnPath, formattedCode, "utf8");
      file.translateEnStatus = true;
      console.log(`SUCCESS translateEnLang ======${file.fullPath}`);
    } catch (error) {
      file.translateEnStatus = false;
      console.error(`ERROR translateEnLang ======${file.fullPath}`);
      console.log(JSON.stringify(file));
      console.error(error);
    }
  }
};

module.exports = translateEnLang;
